﻿using System;
using System.Threading;
using System.Windows;

namespace Reactor.MiniManager.Utility
{
    public static class ThreadDispatches
    {
        /// <summary>
        /// Executes the specified action on the UI thread. If this method is called from a non-WPF application, 
        /// the action will be executed on the current thread and no exception will be thrown.
        /// </summary>
        /// <param name="action">The action.</param>
        public static void ExecuteOnUiThread(Action action)
        {
            if (action == null) throw new ArgumentNullException("action");

            if (Application.Current == null)
                action.Invoke();
            else
                Application.Current.Dispatcher.BeginInvoke(new ThreadStart(action.Invoke));
        }

        /// <summary>
        /// Executes the specified action on the UI thread. If this method is called from a non-WPF application,
        /// the action will be executed on the current thread and no exception will be thrown.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="action">The action.</param>
        /// <param name="actionParameter">The action parameter.</param>
        public static void ExecuteOnUiThread<T>(Action<T> action, T actionParameter)
        {
            if (action == null) throw new ArgumentNullException("action");

            if (Application.Current == null)
                action.Invoke(actionParameter);
            else
                Application.Current.Dispatcher.BeginInvoke(new ThreadStart(() => action.Invoke(actionParameter)));
        }
    }
}
